import urllib, urllib2
import django.utils.simplejson as jsondata
from conf.PicasaConf import PicasaConf
import sys
class PhotoData:

    def processUrl(self,url):
        try:
            f = urllib2.urlopen(url)
            json = f.read()
            #return HttpResponse('Video title: %s' % json)
        
            import re    
            new_str = re.sub('[$]', '', json)
            json = jsondata.JSONDecoder().decode(new_str) 
            return json
        except:
            return '[{"text":"Looks like Twitter is down. Thanks for visiting us. Please try again latter."}]'
            #return sys.exc_info()[1]
            raise


    def getUserName(self):
        conf = PicasaConf()
        userName = conf.getusername()
        return userName
    
    def getDefaultAlbum(self):
        conf = PicasaConf()
        albumid = conf.getalbum()
        return albumid
        
    def getAlbum(self):    
        userName = self.getUserName()
        url = 'http://picasaweb.google.com/data/feed/api/user/'+userName+'?alt=json&kind=album&max-results=6'
        json = self.processUrl(url)
        return json
    
    def getUserTag(self):   
        userName = self.getUserName()
        url = 'http://picasaweb.google.com/data/feed/api/user/'+userName+'?alt=json&kind=tag&max-results=10'
        
        json = self.processUrl(url)
        
        if not json:
            import sys
            print >> sys.stderr, 'No response. Perhaps slideshare down?'
            sys.exit(1)
        return json
    
    def getLatestPhotos(self):
        userName = self.getUserName()  
        url = 'http://picasaweb.google.com/data/feed/api/user/'+userName+'?alt=json&kind=photo&max-results=6'
        json = self.processUrl(url)
        return json   
    
    def getAlbumPhotos(self,albumId):
        userName = self.getUserName()
        url = 'http://picasaweb.google.com/data/feed/api/user/'+userName+'/albumid/'+albumId+'?alt=json&kind=photo&max-results=6'
        json = self.processUrl(url)
        return json
    
    def getTagPhotos(self,tagName):
        userName = self.getUserName()
        url = 'http://picasaweb.google.com/data/feed/api/user/'+userName+'?alt=json&kind=photo&tag='+tagName+'&max-results=6'
        json = self.processUrl(url)
        return json